package xyz.eden.boot.ability.code.generate;

import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import xyz.eden.boot.ability.code.generate.enums.TemplateEngineType;

import java.io.StringWriter;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

@Slf4j
public class VelocityTemplateFromFile implements TemplateFactory {
    @Override
    public void initTemplateEngine() {
        Properties properties = this.getProperties();
        Velocity.init(properties);
    }

    private Properties getProperties() {
        Properties properties = new Properties();
        properties.put(RuntimeConstants.RESOURCE_LOADER, "classpath");
        properties.put("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        properties.put(Velocity.INPUT_ENCODING, Velocity.ENCODING_DEFAULT);
        return properties;
    }

    @Override
    public boolean isSupper(TemplateEngineType engineType) {
        return Objects.equals(engineType, TemplateEngineType.VELOCITY_TEXT);
    }

    @Override
    public String processTemplate(String templateStr, Map<String, Object> dataMap) {
        try {
            // 加载模板
            Template template = Velocity.getTemplate(templateStr);
            // 创建 VelocityContext 实例
            VelocityContext context = new VelocityContext(dataMap);
            // 进行模板合并
            StringWriter writer = new StringWriter();
            template.merge(context, writer);
            return writer.toString();
        } catch (Exception e) {
            log.error("TemplateFromVelocity.processTemplate - template process exception.", e);
            return templateStr;
        }
    }
}
